package com.googlecode.lightest.core

import org.testng.reporters.XMLReporterConfig

/**
 * This testcase class contains helper methods for invoking the runner and
 * analyzing the results of the run.
 */
abstract class RunnerTestCase extends GroovyTestCase {
     public static final TEST_PASSED = XMLReporterConfig.TEST_PASSED
     public static final TEST_FAILED = XMLReporterConfig.TEST_FAILED
     public static final TASK_OK = "${ITaskResult.STATUS_OK}"
     public static final TASK_FAILED = "${ITaskResult.STATUS_FAILED}"
     public static final TASK_DOOMED = "${ITaskResult.STATUS_DOOMED}"
     
     protected RunnerSupport runnerSupport
     
     @Override
     void setUp() {
         super.setUp()
         runnerSupport = new RunnerSupport()
     }
     
     static void assertPrefix(prefix, value) {
         assertEquals(prefix, value.substring(0, prefix.length()))
     }
     
     static void assertSuffix(suffix, value) {
         assertEquals(suffix, value.substring(value.length() - suffix.length()))
     }
     
     /**
      * Asserts that a given test method achieved a given status.
      * 
      * @param status
      * @param root        the root of the testng-results.xml document
      * @param methodName
      */
     static void assertTestMethodStatus(status, Node root, String methodName) {
         assertEquals(status, getTestMethod(root, methodName).'@status')
     }
     
     static def getTestMethods(Node root) {
         def methods = []
         
         for (node in root.depthFirst()) {
             if (node.name() == 'test-method' && node.'@is-config' != 'true') {
                 methods << node
             }
         }
         
         return methods
     }
     
     static def getTestMethod(Node root, String methodName) {
         for (node in getTestMethods(root)) {
             if (node.'@name' == methodName) {
                 return node
             }
         }
         
         return null
     }
     
     /**
      * Returns a "List" of task-result nodes, in the order of appearance, for
      * a given test method. Only top level task-result nodes will be returned;
      * others may be reached by traversing from these nodes.
      * 
      * @param root        the root of the testng-results.xml document
      * @param methodName
      */
     static getTaskResults(Node root, String methodName) {
         return getTestMethod(root, methodName).'task-result'
     }
     
     static getFailedFile() {
         return new File(RunnerSupport.OUTPUT_DIR, RunnerSupport.FAILED_XML)
     }
     
     static getFailedMethods() {
         def failedFile = getFailedFile()
         
         assertTrue(failedFile.exists())
         
         def root = new XmlParser().parse(failedFile)

         return root.test[0].classes[0].class[0].methods[0].include
     }
}
